﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AopFilters.Models
{
    public class ApiResult
    {
        public const string SuccessCode = "success";
        public const string ErrorCodePre = "error-";
        public string Code { get; private set; }

        public string Msg { get; private set; } = "";

        public long TimeStamp { get; init; } = DateTimeOffset.Now.ToUnixTimeSeconds();

        public object? Data { get; private set; }

        public ApiResult(string code, string msg = "", object? data = null)
        {
            Code = code;
            Msg = msg;
            Data = data;
        }

        public static ApiResult Success(object? data = null)
        {
            return new ApiResult(SuccessCode, "", data);
        }

        public static ApiResult Error(string msg, string? errorCode = null)
        {
            return new ApiResult(FixErrorCode(errorCode), msg);
        }

        public static string FixErrorCode(string? errorCode = null)
        {
            errorCode = string.IsNullOrWhiteSpace(errorCode) ? ErrorCode.Normal.ToString() : errorCode;
            return (ErrorCodePre + errorCode).ToLower();
        }

        public void SetErrorCode(string? errorCode = null)
        {
            Code = FixErrorCode(errorCode);
        }
    }
}
